import React from 'react'
import pathToRegexp from 'path-to-regexp'
import { createElement } from 'react'
import _ from 'lodash'

import Loadable from 'react-loadable'
import RouteLoading from 'component/routeLoading'

let routerDataCache

function dynamicWrapper (component) {
  if (component.toString().indexOf('.then(') < 0) {
    return props => {
      if (!routerDataCache) {
        routerDataCache = getRouterData()
      }
      return createElement(component().default, {
        ...props,
        routerData: routerDataCache,
      })
    }
  }

  return Loadable({
    loader: () => {
      if (!routerDataCache) {
        routerDataCache = getRouterData()
      }

      return component().then(v => {
        const Component = v.default || v

        return props => createElement(Component, {
          ...props,
          routerData: routerDataCache
        })
      })
    },
    loading: RouteLoading
  })
}

const routerConfig = {
  '/': {
    component: dynamicWrapper(() => import('container/login'))
  },
  '/home': {
    component: dynamicWrapper(() => import('container/home'))
  },
  '/house': {
    component: dynamicWrapper(() => import('../layout/house')),
  },
  '/house/choice': {
    component: dynamicWrapper(() => import('container/house/choice')),
  },
  '/house/alternative': {
    component: dynamicWrapper(() => import('container/house/alternative')),
  },
  '/house/i': {
    component: dynamicWrapper(() => import('container/house/i')),
  },
  '/pay': {
    component: dynamicWrapper(() => import('container/pay')),
  }
}

export const getRouterData = () => {
  return routerConfig
}
